/*
 * @Author: 0x9DEFA478
 * @Date: 2025-10-03 21:07:01
 * @LastEditTime: 2025-10-03 21:17:31
 * @LastEditors: 0x9DEFA478
 * @Description: 
 * 
 */
#include "./DeviceEnum.hpp"
#if defined(_WIN32)
#include "H_Pointer.hpp"
#include "Utility/H_String.hpp"
#include "./Encoding.hpp"
// #include <initguid.h>
// #include <Usbiodef.h>
#include <stdexcept>
#endif




namespace SystemAPI{

  namespace Windows{

#if defined(_WIN32)
    std::list<std::string> EnumDevice_ByGUID(const GUID* guid){
      ULONG p_ulLen;
      ULONG ulFlags;
      H::Pointer<WCHAR> Buffer;
      CONFIGRET res;

      ulFlags=CM_GET_DEVICE_INTERFACE_LIST_PRESENT;
      do{
        GUID guid_temp=*guid;

        res=CM_Get_Device_Interface_List_SizeW(&p_ulLen,&guid_temp,nullptr,ulFlags);

        if(CR_SUCCESS!=res){
          throw std::runtime_error(H::String::Format("CM_Get_Device_Interface_List_SizeW 失败:%08lX",res));
        }

        if(Buffer.Length()<p_ulLen){
          Buffer=Buffer.Array(p_ulLen);
        }
        memset(Buffer,0,Buffer.Length()*sizeof(Buffer[0]));

        res=CM_Get_Device_Interface_ListW(&guid_temp,nullptr,Buffer,p_ulLen,ulFlags);
      }while(res==CR_BUFFER_SMALL);

      if(res!=CR_SUCCESS){
        std::runtime_error(H::String::Format("CM_Get_Device_Interface_ListW 失败:%08lX",res));
      }

      std::list<std::string> r;
      ULONG sIndex=0;
      ULONG index=0;
      
      while(index<p_ulLen){
        if(Buffer[index]==0){

          auto path=TextConvertFromWideString(CP_UTF8,&Buffer[sIndex]);
          if(path.length()>0){
            r.emplace_back(path);
          }
      
          index++;
          sIndex=index;
        }else{
          index++;
        }
      }

      return r;
    }
#endif

  }

}



